﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Sgr.Data;
using Sgr.EntityFrameworkCore.EntityConfigurations;
using Sgr.EventBus.RelayBoxs.Domain;

namespace Sgr.EventBus.RelayBoxs.Infrastructure.EntityConfigurations
{
    public class OutboxMessageConfiguration : EntityTypeConfigurationBase<OutboxMessage, long>
    {
        public OutboxMessageConfiguration(DatabaseType? databaseType = null) : base(databaseType)
        { }

        public override void Configure(EntityTypeBuilder<OutboxMessage> builder)
        {
            builder.ToTable("sgr_outbox_message");

            base.Configure(builder);

            builder.Property(b => b.MessageTopic)
                .HasColumnName("sqr_topic")
                .HasMaxLength(128)
                .IsRequired()
                .HasComment("消息主题");

            // 基本字段
            builder.Property(b => b.MessageType)
                .HasColumnName("sqr_type")
                .HasMaxLength(200)
                .IsRequired()
                .HasComment("消息类型");

            builder.Property(b => b.MessageId)
                .HasColumnName("sqr_message_id")
                .HasMaxLength(64)
                .IsRequired()
                .HasComment("消息唯一标识");

            // Payload：优先使用数据库原生 JSON 类型，回退为文本
            var payloadProp = builder.Property(b => b.Payload)
                .HasColumnName("sqr_payload")
                .IsRequired()
                .HasComment("消息载荷（JSON）");

            ConfigureJsonColumn(payloadProp, Constant.ExtendableObjectMaxLength);

            // 时间字段
            builder.Property(b => b.OccurredOnUtc)
                .HasColumnName("sqr_occurred_on_utc")
                .IsRequired()
                .HasComment("发生时间（UTC）");

            builder.Property(b => b.NextOnUtc)
                .HasColumnName("sqr_next_on_utc")
                .IsRequired()
                .HasComment("下一次尝试投递时间（UTC）");

            builder.Property(b => b.DispatchedOnUtc)
                .HasColumnName("sqr_dispatched_on_utc")
                .HasComment("实际投递时间（UTC），为空表示未投递");

            // 状态与重试计数
            builder.Property(b => b.Status)
                .HasColumnName("sqr_status")
                .IsRequired()
                .HasComment("消息状态");

            builder.Property(b => b.RetryCount)
                .HasColumnName("sqr_retry_count")
                .IsRequired()
                .HasComment("重试次数");

            // 错误信息
            builder.Property(b => b.LastError)
                .HasColumnName("sqr_last_error")
                .HasMaxLength(2000)
                .HasComment("上次投递失败错误信息");

            // 索引：复合索引（状态 + 下次投递时间），以及消息 ID 唯一索引
            builder.HasIndex(b => new { b.Status, b.NextOnUtc })
                .HasDatabaseName("ix_outbox_message_status_next_on_utc");

            builder.HasIndex(b => b.MessageId)
                .IsUnique()
                .HasDatabaseName("ux_outbox_message_message_id");
        }
    }
}